package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.domain.Member;
import com.itheima.domain.Order;
import com.itheima.domain.OrderSetting;
import com.itheima.message.MessageConstant;
import com.itheima.result.Result;
import com.itheima.service.OrderService;
import com.itheima.utils.DateUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl  implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    private InterProcessMutex lock;

    public OrderServiceImpl(){
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(3000, 10);
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
        lock=new InterProcessMutex(client,"/lock");
    }
    @Override
    public Result order(Map map) throws Exception {
        Order order=null;
        try {
            lock.acquire(3, TimeUnit.SECONDS);
            //获取预约时间
            String orderDate = (String) map.get("orderDate");
            //转换时间格式类型
            Date date = DateUtils.parseString2Date(orderDate);
            System.out.println(date+"bbbbbbbbbbb");
            //调用orderSettingDao中的方法，查询当天是否可以预约
            OrderSetting orderSetting = orderSettingDao.findCountByOrderDate(date);
            System.out.println(orderSetting+"==========");
            //判断，为null时，当天没有预约设置
            if (orderSetting==null){
                //返回
                return new Result(false,
                        MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //获取预约总人数
            int number = orderSetting.getNumber();
            //获取已经预约人数
            int reservations = orderSetting.getReservations();
            //判断
            if (reservations>=number){
                return new Result(false,MessageConstant.ORDER_FULL);
            }
            //获取电话号码
            String telephone = (String) map.get("telephone");
            //调用memberDao方法获取会员信息
            Member member=memberDao.findByTelephone(telephone);
           //判断
           if (member!=null){
               //不为null，封装会员ID，套餐ID，时间
               Integer memberId = member.getId();
               int setmealId = Integer.parseInt((String) map.get("setmealId"));
               order = new Order(memberId, date, setmealId);
               //调用orderDao，根据会员ID，套餐ID，时间查询
               List<Order> list=orderDao.findByCondition(order);
               //当返回值不为null时，返回不可重复预约
               if (list!=null&&list.size()>0){
                   return new Result(false,MessageConstant.HAS_ORDERED);
               }
        }
            //封装已预约人数+1
            orderSetting.setReservations(orderSetting.getReservations()+1);
            orderSettingDao.editReservationsByOrderDate(orderSetting);
            //判断，当会员信息查询为null时，自动添加会员信息
            if (member==null){
                member = new Member();
                member.setName((String) map.get("name"));
                member.setPhoneNumber(telephone);
                member.setIdCard((String) map.get("idCard"));
                member.setSex((String) map.get("sex"));
                member.setRegTime(new Date());
                memberDao.add(member);
            }
            //封装预约信息
            order = new Order(member.getId(), date, (String) map.get("orderType"), Order.ORDERSTATUS_NO, Integer.parseInt((String) map.get("setmealId")));
            //调用Dao方法添加信息
            orderDao.add(order);
        }catch (Exception e){
           e.printStackTrace();
        }finally {
            lock.release();
        }
        return new Result(true,MessageConstant.ORDER_SUCCESS,order.getId());
    }

    @Override
    public Map findById(Integer id) throws Exception {
        Map map=orderDao.findById4Detail(id);
        if(map != null){
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate",DateUtils.parseDate2String(orderDate));
        }
        return map;
    }
}
